package com.cjh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjh.annotation.WebLog;
import com.cjh.pojo.EChartPie;
import com.cjh.pojo.Goods;
import com.cjh.pojo.Type;
import com.cjh.service.GoodsService;
import com.cjh.service.OrderService;
import com.cjh.service.TypeService;
import com.cjh.utils.RedisUtil;
import com.cjh.vo.ResultMap;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/goodsApi")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisUtil redisUtil;

    private static Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @GetMapping("/goodsList")
    @WebLog(description = "请求=>查询所有商品接口")
    public ResultMap goodsList(@RequestParam(value = "page", defaultValue = "1",required = false) Integer page
            , @RequestParam(value = "limit", defaultValue = "10",required = false) Integer limit
            , Goods searchGoods) {
        PageHelper.startPage(page, limit);
        List<Goods> goods = goodsService.selectGoodsPaging(searchGoods);
        PageInfo<Goods> pageInfo = new PageInfo<>(goods);

        return ResultMap.ok(0, "所有商品信息->每页10条数据", pageInfo.getList(), (int) pageInfo.getTotal());
    }

    @PostMapping("/get")
    @WebLog(description = "请求=>根据id查看商品详情")
    public ResultMap get(@RequestParam(value = "id",required = false) Integer id) {
        Goods goods = goodsService.getGoods(id);

        return ResultMap.ok(0, "根据id查看菜品详情", goods, 1);
    }

    @PostMapping("/insertGoods")
    @WebLog(description = "请求=>添加商品接口")
    public ResultMap insertGoods(Goods goods){
        boolean flag = goodsService.save(goods);

        return ResultMap.ok(200,"添加一个商品","添加成功",1);

    }

    @DeleteMapping("/deleteGoodsById")
    @WebLog(description = "请求=>删除商品接口")
    public ResultMap deleteGoodsById(HttpServletRequest request, @RequestParam(value = "ids",required = false) List<Integer> ids){

        logger.info(ids.size()>1 ? "批量删除" : "单个删除");
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.in("id",ids);
        //先查出要删除的商品名称,后续才可以删除图片
        List<Goods> goods = goodsService.list(queryWrapper);
        //删除
        boolean flag = goodsService.removeByIds(ids);
        //成功再删除图片和redis
        if (flag){
            for (Goods good : goods) {
                if (!ObjectUtils.isEmpty(redisUtil.get("goods:"+good.getId()))){
                    redisUtil.del("goods:"+good.getId());
                }
                //原路径：http://localhost:8005/uploadFile/xxxxxxx.png
//                StringBuffer sb=new StringBuffer(good.getPicture());
                //pictureUrl：xxxxxxx.png
//                String pictureUrl=sb.substring(sb.lastIndexOf("/"));
//                deletePicture(request,pictureUrl);
            }
        }

        return ResultMap.ok(200,"根据id删除商品","删除成功");
    }

    @PutMapping("/updateGoodsById")
    @WebLog(description = "请求=>修改商品接口")
    public ResultMap updateGoodsById(Goods goods){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select("name").eq("id", goods.getTypeId());
        Type type = typeService.getOne(queryWrapper);
        //设置分类id
        goods.setTypeId(goods.getTypeId());
        //设置分类实体
        goods.setType(new Type(goods.getTypeId(),type.getName()));

        boolean flag = goodsService.updateById(goods);
        //更新缓存
        redisUtil.set("goods:"+ goods.getId(), goods);
        return ResultMap.ok(200,"修改一个商品","修改成功",1);
    }

    @GetMapping("/typeList")
    @WebLog(description = "请求=>查询所有分类接口")
    public ResultMap typeList() {
        List<Object> redisTypes = redisUtil.lGet("types",0,-1);
        if (!redisTypes.isEmpty()){
            logger.info("===从redis获取===");
            return ResultMap.ok(0, "所有分类信息", redisTypes, redisTypes.size());
        }
        List<Type> types = typeService.list();
        redisUtil.lSet("types",types);
        logger.info("===从数据库获取===");
        return ResultMap.ok(0, "所有分类信息", types, types.size());
    }

    public void deletePicture(HttpServletRequest request, String fileName){
        String realPath = request.getServletContext().getRealPath("/upload");
        File file=new File(realPath+fileName);
        if (!Objects.isNull(file)){
            if(file.exists()){
                file.delete();
                logger.info("图片已删除");
            }
        }else{
            logger.debug("图片不存在");
        }

    }

    @GetMapping("/getBarEChartData")
    @WebLog(description = "请求=>查询柱状图数据")
    public ResultMap getBarEChartData(){

        Map<String,Object> map=new LinkedHashMap<>();

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select("name");
        List<Type> types=typeService.list(queryWrapper);

        List<String> typeName=new ArrayList<>();

        List<Integer> goodsCount=new ArrayList<>();

        List<Integer> orderCount=new ArrayList<>();
        for (Type type : types) {
            typeName.add(type.getName());
            goodsCount.add(goodsService.getGoodsCountByTypeName(type.getName()));
            orderCount.add(orderService.getOrderCountByTypeName(type.getName()));
        }
        //x轴分类名称数据
        map.put("typeName",typeName);
        //x轴每个条形对应的菜品数量
        map.put("goodsCount",goodsCount);
        //x轴每个条形对应的订单数量
        map.put("orderCount",orderCount);
        return ResultMap.ok(200,"查询柱状图数据", map);
    }

    @GetMapping("/getPieEChartData")
    @WebLog(description = "请求=>查询饼图数据")
    public ResultMap getPieEChartData(){

        List<EChartPie> list=new ArrayList<>();

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select("name");
        List<Type> types=typeService.list(queryWrapper);

        for (Type type : types) {
            EChartPie eChartPie=new EChartPie();
            //分类名称
            eChartPie.setName(type.getName());
            //每个分类对应的菜品数量
            eChartPie.setValue(goodsService.getGoodsCountByTypeName(type.getName()));
            list.add(eChartPie);

        }
        return ResultMap.ok(200,"查询饼图数据",list);
    }
}
